// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

cc.Class({
    extends: cc.Component,

    properties: {
        
        nodeArr: null,
        newFbo: null,
        oldFbo: null,
        texture: null,
        frameCount: 0,
        sp: cc.Sprite,
        startTime: null,
        oldY: 0.0,
        vs: null,
        fs: null,
        
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () 
    {
        var gl = cc._renderContext;
        this.vs = 
        "attribute vec4 a_position;\n"+
        "varying vec2 v_texcoord;\n"+
        "void main() {\n"+
        "gl_Position = a_position;\n"+
        "v_texcoord = a_position.xy;\n"+
        // "v_texcoord = a_position.xy * 0.5 + 0.5;\n"+
        "}\n";

        this.fs = 
        "precision mediump float;\n"+
        "varying vec2 v_texcoord;\n"+
        "uniform sampler2D u_sampler;\n"+
        "void main() {\n"+
        "gl_FragColor = texture2D(u_sampler, v_texcoord);\n"+
        "}\n";
        this._program = gl.createProgram();
        this.verShader = this.createShader(gl, this.vs, gl.VERTEX_SHADER);
        this.fragShader = this.createShader(gl, this.fs, gl.FRAGMENT_SHADER);
        gl.attachShader(this._program, this.verShader);
        gl.attachShader(this._program, this.fragShader);
        gl.linkProgram(this._program);
        if (!gl.getProgramParameter(this._program, gl.LINK_STATUS)) {
            var info = gl.getProgramInfoLog(this._program);
            throw 'Could not compile WebGL program. \n\n' + info;
        }

        this.startTime = new Date().getTime();
        this.oldY = this.node.y;
        
        // gl.clearColor(1.0, 1.0, 1.0, 1.0);
        this.nodeArr = [];
        this.newFbo = gl.createFramebuffer();
        
        this.texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, this.texture);
        var size = cc.director.getWinSizeInPixels();
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size.width, size.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);  

        this.pushNode(this.node); 


       

        
    },

    start () 
    {

    },

    update (dt)
    {

        var deltaTime = new Date().getTime() - this.startTime;
        // var pos = this.node._position;
        this.node.y = this.oldY + 120.0 * Math.sin(deltaTime / 1000.0 * 3);
        this.frameCount++;

        var val = this.frameCount % 100000;
        // if(val < 2)
        {
            // return;
            this.begin();

            this.render();

            


            

            this.end();
            cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
            cc.math.glPushMatrix();
            cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
            cc.math.glPushMatrix();
            // var verts = [
            //     1, 1,
            //     -1, 1,
            //     -1, -1,
            //     1, 1,
            //     -1, -1,
            //     1, -1,
            // ];
            var verts = [
                0.0,  0.0,
                1.0,  0.0,
                0.0,  1.0,
                0.0,  1.0,
                1.0,  0.0,
                1.0,  1.0
            ];
            var gl = cc._renderContext;
            gl.useProgram(this._program);
    
            var vertBuffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);

            var a_Position = gl.getAttribLocation(this._program, 'a_position');
            gl.enableVertexAttribArray(a_Position);
            gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    
    
            gl.clearColor(1, 0, 0, 1); // red
            gl.clear(gl.COLOR_BUFFER_BIT);
            gl.bindTexture(gl.TEXTURE_2D, this.texture);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
            cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
            cc.math.glPopMatrix();
            cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
            cc.math.glPopMatrix();
        }
        
    },

    begin()
    {
        cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
        cc.math.glPushMatrix();
        cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
        cc.math.glPushMatrix();

        var gl = cc._renderContext;

        var director = cc.director;
        director.setProjection(director.getProjection());

        // Calculate the adjustment ratios based on the old and new projections
        // var size = cc.director.getWinSizeInPixels();
        // var widthRatio = size.width / node._texture.width;
        // var heightRatio = size.height / node._texture.height;

        /*var orthoMatrix = cc.math.Matrix4.createOrthographicProjection(-1.0 / widthRatio, 1.0 / widthRatio,
            -1.0 / heightRatio, 1.0 / heightRatio, -1, 1);
        cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
        cc.math.glMultMatrix(orthoMatrix);

        //calculate viewport
        var viewport = new cc.Rect(0, 0, 0, 0);
        viewport.width = this._fullViewport.width;
        viewport.height = this._fullViewport.height;
        var viewPortRectWidthRatio = viewport.width / this._fullRect.width;
        var viewPortRectHeightRatio = viewport.height / this._fullRect.height;
        viewport.x = (this._fullRect.x - this._rtTextureRect.x) * viewPortRectWidthRatio;
        viewport.y = (this._fullRect.y - this._rtTextureRect.y) * viewPortRectHeightRatio;
        gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);*/

        this.oldFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING);
        gl.bindFramebuffer(gl.FRAMEBUFFER, this.newFbo);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);  
    },

    end()
    {
        var gl = cc._renderContext;
        var director = cc.director;
        gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
    
        //restore viewport
        director.setViewport();
        cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
        cc.math.glPopMatrix();
        cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
        cc.math.glPopMatrix();
    },


    render()
    {
        var gl = cc._renderContext;

        var len = this.nodeArr.length;
        for(var i=0; i<len; i++)
        {
            var getNode = this.nodeArr[i];
            var getsgNode = getNode._sgNode;
            // getsgNode.visit(_sgNode.getParent());
            getsgNode.visit();
        }

      


    },

    //添加要渲染的残影Node
    pushNode(node)
    {
        this.nodeArr.push(node);
    },

    createShader(gl, sourceCode, type)
    {
        var shader = gl.createShader( type );
        gl.shaderSource( shader, sourceCode );
        gl.compileShader( shader );
      
        return shader;
    },


});
